import React from 'react'
import { Upload, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import Cloud from 'leancloud-storage'
function getBase64(img, callback) {  //将Upload组件得到的本地图片，转化为base64编码
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

function beforeUpload(file) {  //限制文件类型
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
}

class ImgUpload extends React.Component {
  state = {
    loading: false,
  };
  customRequest = (info)=>{  //自定义上传逻辑代码
    console.log(info);
    getBase64(info.file,(imgstr)=>{
      console.log(imgstr); //imgstr就是获取到的base64编码字符串
      const data = { base64: imgstr };
      const file = new Cloud.File('pic.png', data); //构建可用于上传的File对象
      file.save().then((file) => {  //向LeanCloud发起存储异步请求
        console.log('图片上传成功',file);
        let { url } = file.attributes
        this.setState({ //将在线图片链接，设置为预览图
          imageUrl:url
        })
        this.props.handleImgUrl(url)  //触发父级的方法函数，传递图片路径
      }, (error) => {
        console.log(error);
        // 保存失败，可能是文件无法被读取，或者上传过程中出现问题
      });
    })
  }
  componentDidUpdate(){
    console.log('ImgUpload', this.props);
    // let {imgUrl} = this.props
    let {imageUrl} = this.state;
    let {imgUrl} = this.props;
    if(imgUrl!=imageUrl){ //如果不做判断，则Update生命周期会进入死循环
      this.setState({  
        imageUrl: this.props.imgUrl  //通过父级组件传递的图片路径，设置预览图
      })
    }
  }
  render() {
    
    const { loading, imageUrl } = this.state;
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );
    return (
      <Upload
        name="avatar"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        beforeUpload={beforeUpload}
        customRequest={this.customRequest}
      >
        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
      </Upload>
    );
  }
}

export default ImgUpload